var currentClass;
var myClassesCache; // global var to cache the user's class list
var allClassesCache; // global var to cache the full class list
var userName;	// store the username on the client - only used with like/liked for now (11/22/09)
var isProfessor = false;

// jqtouch initialization
var jQT = new $.jQTouch(
	{
		icon: 'images/ii-icon.png',
		startupScreen: 'images/instantinput-startup.png'
	}
);

// This function is just for testing: allows us to append ?testingUserType=professor
// to the end of the app URL to test as a professor
function testingUserType()
{
	var query = window.location.search.substring(1);
	var parms = query.split('&');
	for (var i=0; i<parms.length; i++)
	{
		var pos = parms[i].indexOf('=');
		if (pos > 0)
		{
			var key = parms[i].substring(0,pos);
			var val = parms[i].substring(pos+1);
			
			if (key == 'testingUserType')
			{
				return val;
			}
		}
	}
}

// function to return the full class list with optional filtering
function filteredAllClassesList(filterText)
{
	var newList = $('<ul id="allClassesList"></ul>');
	var count = 0;
	for (var c in allClassesCache)
	{
		var course = allClassesCache[c].course;
		if(!filterText)
		{
			$('<li class="allClassesItem arrow" id="' + c + '">' + course + '</li>').appendTo(newList);
			count++;
		}
		else
		{
			var match = course.indexOf(filterText);
			if(match != -1) { 
				$('<li class="allClassesItem arrow" id="' + c + '">' + course + '</li>').appendTo(newList);
				count++;
		    }
		}
	}
	if (count == 0) 
	    $('<li>No matches found</li>').appendTo(newList);
	    
	return newList;
}

// this function binds mouseup events to the items in the "All Classes" list
// It defines a callback that sets up the "Add Existing Detail View" screen when a class is selected from the list
function bindClickToAllClassesItems()
{
	// bind the click action to the new list items
	$('li[class="allClassesItem arrow"]').bind('mouseup',
		function(event)
		{
			var index = $(this).attr('id');
			var title = allClassesCache[index].title;
			var course = allClassesCache[index].course;
			var startTime = allClassesCache[index].startTime;
			var endTime = allClassesCache[index].endTime;
			var location = allClassesCache[index].location;
			var days = allClassesCache[index].days;
			var uniqueCourseNumber = allClassesCache[index].uniqueCourseNumber;

			// set up the addExistingDetailView screen
			var addExistingDetailViewDiv = $('#addExistingDetailView');
			addExistingDetailViewDiv.empty(); // empty it before using it
			var navBarDiv = $('<div class="toolbar"></div>').appendTo(addExistingDetailViewDiv);
			var navBarContents = $('<h1>' + allClassesCache[index].course + '</h1><a class="back">Select a Class</a>').appendTo(navBarDiv);
			
			var newList = $('<ul></ul>').appendTo(addExistingDetailViewDiv);
			$('<li>'
				+ course + '<br />'
				+ title + '<br />'
				+ location + '<br />'
				+ startTime + ' - '
				+ endTime + ' on '
				+ days
				+ '</li>').appendTo(newList);

			var addButtonList = $('<ul></ul>').appendTo(addExistingDetailViewDiv);
			$('<li class="liButton">Add Class</li>').appendTo(addButtonList).bind('mouseup',{uniqueCourseNumber: uniqueCourseNumber},
				function(event)
				{
					// to prevent double-tapping the button and submitting the request to the server multiple times
					// Disable the button as soon as it is clicked
					var newListItem = $('<li class="liButtonInactive">Adding Class...</li>');
					$(this).replaceWith(newListItem);
					
					// this getJSON call gets the user's class list from the server in JSON form
					$.getJSON('php/addClass.php', {uniqueCourseNumber: event.data.uniqueCourseNumber},
						function(response)
						{
							myClassesCache = response;	// cache the response on the device in a global var
							
							var newList = myClassesList();	// get the html for the user's class list
							$('#myClassesList').replaceWith(newList);	// update the existing empty list with the new html
							bindClickToMyClassesItems(); // re-bind click and touch events to the my classes list items
							
							jQT.goBackPro(2,'slideup',true);
						}
					);
				}
			);
			
			jQT.goTo('#addExistingDetailView', 'slide');
		}
	);
}

// function to return the user's class list in html
function myClassesList()
{
	var newList = $('<ul id="myClassesList"></ul>');
	
	for (var c in myClassesCache)
	{
		var course = myClassesCache[c].course;
		$('<li class="myClassesItem arrow" id="' + c + '">' + course + '</li>').appendTo(newList);
	}
	
	if(myClassesCache.length == 0)
	{
		var link = $('a[id="homeScreenAddButton"]').attr('href');
		
		// add a placeholder that says they need to join a class
		$('<li><a href="' + link + '">You are not part of any classes.<br />Tap here to add one.</a></li>').appendTo(newList);
		
		// take them to the add class page automatically
		jQT.goTo(link, 'slideup');
	}
	
	return newList;
}

// this function binds mouseup events to the items in the "My Classes" list
// It defines a callback that sets up the "In Class" screen when a class is selected from the list
function bindClickToMyClassesItems()
{
	// bind the click action to the new list items
	$('li[class="myClassesItem arrow"]').bind('mouseup',
		function(event)
		{
			var index = $(this).attr('id');
			currentClass = myClassesCache[index];	// remember which class we're headed to

			// set up the metrics and messages views' titles
			var metricsViewDiv = $('#metricsView');
			$('div[class="toolbar"] > h1', metricsViewDiv).text(currentClass.course);
			var threadListViewDiv = $('#threadListView');
			$('div[class="toolbar"] > h1', threadListViewDiv).text(currentClass.course);
			var messageListViewDiv = $('#messageListView');
			$('div[class="toolbar"] > a[class="back"]',messageListViewDiv).text(currentClass.course);
			
			// load messages for this class
			initializeSliders();
			loadMessages();
			
			jQT.goTo('#metricsView', 'slide');
		}
	);
}

function postReplyButtonClicked(event)
{
	jQT.goTo('#postReply', 'slideup');
}

function postNewThreadButtonClicked(event)
{
	jQT.goTo('#postNewThread', 'slideup');
}

// the ready function runs right after the page loads
$(document).ready(
	function()
	{
		// initialize the polling, and data loading for in-class views
		$('#metricsView').bind('pageAnimationEnd', togglePolling);
		$('#messageListView').bind('pageAnimationEnd', toggleMessagesPollingForDetailView);
		
		// bind to the post reply and post new thread buttons
		$('#postReplyButtonTop').bind('mouseup',postReplyButtonClicked);
		$('#postReplyButtonBottom').bind('mouseup',postReplyButtonClicked);
		$('#postNewThreadButtonOne').bind('mouseup',postNewThreadButtonClicked);
		$('#postNewThreadButtonTwo').bind('mouseup',postNewThreadButtonClicked);
		
		// bind to the submit reply and new thread buttons
		$('#submitReplyButton').bind('mouseup', submitReply);
		$('#submitNewThreadButton').bind('mouseup', submitNewThread);
		
		// bind the slider bars to the orientation change event
		$('body').bind('turn', updateSliderBarBackground);
		
		// set the href attribute of the '+' button on the home screen
		// based on whether the user is a student or professor
		$.get('php/addScreenID.php',{testingUserType: testingUserType()},
			function(data)
			{
				$('a[id="homeScreenAddButton"]').attr('href',data);
				
				// set a global var so we can know if the user is a prof or not
				if(data == '#createNew')
					isProfessor = true;
			}
		);
		
		// Get the user's class list from the server in JSON form
		$.getJSON('php/classesForUser.php',
			function(response)
			{
				myClassesCache = response;	// cache the response on the device in a global var
				
				var newList = myClassesList();	// get the html for the user's class list
				$('#myClassesList').replaceWith(newList);	// update the existing empty list with the new html
				bindClickToMyClassesItems(); // re-bind click and touch events to the my classes list items
			}
		);
		
		// set the href attribute of the '+' button on the home screen
		// based on whether the user is a student or professor
		$.get('php/userName.php',
			function(response)
			{
				userName = response;
			}
		);
		
		// Add Existing page loaded
		$('#addExisting').bind('pageAnimationEnd',
			function(info,direction)
			{
				if(direction.direction === 'in')	// only do this if the page is loading. no need if it's going away
				{
					if(!allClassesCache)
					{
						$.getJSON('php/allClasses.php',
							function(response)
							{
								allClassesCache = response;	// cache the response on the device in a global var
								
								var newList = filteredAllClassesList();	// get the html for the All classes list
								$('#allClassesList').replaceWith(newList);	// update the existing list with the new html
								bindClickToAllClassesItems(); // re-bind click and touch events to the all classes list items
							}
						);
					}
					else
					{
						var newList = filteredAllClassesList();	// get the html for the All Classes List
						$('#allClassesList').replaceWith(newList);	// update the existing list with the new html
						bindClickToAllClassesItems(); // re-bind click and touch events to the all classes list items
					}
					
					$('#searchfield').val('');	// clear any existing text in the search field
				}
			}
		);
		
		// filter the class list after each key stroke
		$('#searchfield').keyup(
			function(event)
			{
				var text = $('#searchfield').val();
				
				var newList = filteredAllClassesList(text); // get the html for the filtered all classes list
				$('#allClassesList').replaceWith(newList);	// update the existing list with the new html
				bindClickToAllClassesItems(); // re-bind click and touch events to the all classes list items
			}
		);
		
		// process the submission of the create form
		$('#createFormSubmit').bind('mouseup',
			function(event)
			{
				// using the jquery.form plugin here for its formToArray() function
				var formDataArray = $('#createForm').formToArray();
				
				// combine the form input into a more useful object
				var combinedFormData = {
					course: '',
					title: '',
					location: '',
					startTime: '',
					endTime: '',
					days: '',
					feedback: new Array()
				};
				for (var e in formDataArray)
				{
					if(formDataArray[e].name == 'days')
						combinedFormData.days = combinedFormData.days + formDataArray[e].value;
					else if(formDataArray[e].name == 'feedback')
						combinedFormData.feedback.push(formDataArray[e].value);
					else
						combinedFormData[formDataArray[e].name] = formDataArray[e].value;
				}
				
				// set up the confirmation screen
				var createNewConfirmationDiv = $('#createNewConfirmation');
				createNewConfirmationDiv.empty(); // empty it before using it
				var navBarDiv = $('<div class="toolbar"></div>').appendTo(createNewConfirmationDiv);
				var navBarContents = $('<h1>Confirm</h1><a class="back">New Class</a>').appendTo(navBarDiv);
				
				var newList = $('<ul></ul>').appendTo(createNewConfirmationDiv);
				$('<li>'
					+ combinedFormData.course + '<br />'
					+ combinedFormData.title + '<br />'
					+ combinedFormData.location + '<br />'
					+ combinedFormData.startTime + ' - '
					+ combinedFormData.endTime + ' on '
					+ combinedFormData.days
					+ '</li>'
					+ '<li>Feedback Types:</li>').appendTo(newList);
				for(var f in combinedFormData.feedback)
					$('<li>' + combinedFormData.feedback[f] + '</li>').appendTo(newList);
				
				var addButtonList = $('<ul></ul>').appendTo(createNewConfirmationDiv);
				$('<li class="liButton">Create Class</li>').appendTo(addButtonList).bind('mouseup',combinedFormData,
					function(event)
					{
						// to prevent double-tapping the button and submitting the request to the server multiple times
						// Disable the button as soon as it is clicked
						var newListItem = $('<li class="liButtonInactive">Creating Class...</li>');
						$(this).replaceWith(newListItem);

						// this getJSON call gets the user's class list from the server in JSON form
						$.getJSON('php/createClass.php', combinedFormData,
							function(response)
							{
								myClassesCache = response;	// cache the response on the device in a global var
								
								var newList = myClassesList();	// get the html for the user's class list
								$('#myClassesList').replaceWith(newList);	// update the existing empty list with the new html
								bindClickToMyClassesItems(); // re-bind click and touch events to the my classes list items
							}
						);
						
						jQT.goBackPro(2,'slideup',true);
					}
				);
				
				jQT.goTo('#createNewConfirmation', 'slide');
				
				return false;
			}
		);
		
	}
);